<template>
  <!-- 增加、编辑商城客户 -->
  <el-dialog :title="dialogTitle" :visible.sync="formDialogVisible" top="0%" custom-class='dialog_right dialogScroll_add MkStoreCustomerMgt' @open="openDialog" @close="closeDialog('customerForm')">
    <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight -200)+'px'}]">
      <el-form :model="customerInfo" :rules="customerInfoRules" ref="customerForm" label-width="110px" style="width:96%;">

        <h5>基本信息</h5>
        <el-form-item label="客户类型" prop='sellerType'>
          <el-select  placeholder="请选择（必选）" v-model='customerInfo.sellerType'>
            <el-option label="自营店铺" value="SELFSTORE"></el-option>
            <el-option label="三方店铺" value="THREESTORE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称" prop="name">
          <el-input v-model='customerInfo.name' placeholder="请输入客户名称（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model='customerInfo.shopName' placeholder="请输入店铺名称（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="票据抬头" prop="billHeader">
          <el-input v-model='customerInfo.billHeader' placeholder="请输入票据抬头（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="社会信用代码" prop="creditCode">
          <el-input v-model='customerInfo.creditCode' placeholder="请输入社会信用代码（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model='customerInfo.contact' placeholder="请输入联系人（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input v-model='customerInfo.contactPhone' placeholder="请输入联系人电话（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="所在城市" prop="citySelectArr">
          <el-cascader
            :options="cityArr"
            :props = 'options'
            placeholder="请选择所在城市（必选）"
            v-model="customerInfo.citySelectArr">
          </el-cascader>
        </el-form-item>
        <el-form-item label="服务站点" prop="siteSelectArr">
          <el-select v-model="customerInfo.siteSelectArr" multiple placeholder="请选择服务站点（必选）">
            <el-option-group
              v-for="group in siteArr"
              :key = 'group.id'
              :label="group.name">
              <el-option
                v-for="item in group.children"
                :label="item.name"
                :key = 'item.id'
                :value="item.id">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>

        <h5>管理员信息</h5>
        <el-form-item label="超级管理员" prop="adminName">
          <el-input v-model='customerInfo.adminName' placeholder="请输入超级管理员（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="adminIdCard">
          <el-input v-model='customerInfo.adminIdCard' placeholder="请输入身份证号（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="adminPhone">
          <el-input v-model='customerInfo.adminPhone' placeholder="请输入联系电话（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="password" v-if="isAdd">
          <el-input v-model='customerInfo.password' type="password" placeholder="请输入登录密码（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="支付Key" prop="payKey">
          <el-input v-model.trim='customerInfo.payKey' :maxlength="50" placeholder="请输入支付Key（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="支付密钥" prop="paySecret">
          <el-input v-model.trim='customerInfo.paySecret' :maxlength="50"  placeholder="请输入支付密钥（必填）">
          </el-input>
        </el-form-item>

        <h5>转账信息</h5>
        <el-form-item label="公司名称" prop="company">
          <el-input v-model='customerInfo.company' placeholder="请输入公司名称（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="银行卡号" prop="bankCardNumber">
          <el-input v-model='customerInfo.bankCardNumber' :maxlength="30" placeholder="请输入银行卡号（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="交易银行" prop="tradingBank">
          <el-input v-model='customerInfo.tradingBank' placeholder="请输入交易银行（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="所在地" prop="bankAddress">
          <el-input v-model='customerInfo.bankAddress' placeholder="请输入所在地（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="开户支行" prop="openBankBranch">
          <el-input v-model='customerInfo.openBankBranch' placeholder="请输入开户支行（必填）">
          </el-input>
        </el-form-item>

      </el-form>
    </el-scrollbar>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" class="btn-primary" :disabled="isSubmitLoading" @click="submitCustomerForm('customerForm')">提交</el-button>
      <el-button type='primary' class="btn-cancel" @click="closeDialog('customerForm')">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import customerService from '../../../services/customer'
import { mapState } from 'vuex'
import ElFormItem from "../../../../node_modules/element-ui/packages/form/src/form-item";
export default {
  components: {ElFormItem}, name: 'MkStoreCustomerMgt',

  props: ['dialogVisible', 'isAdd', 'sellerDetail'],

  watch: {
    dialogVisible: function(value) {
      this.formDialogVisible = value;
    },
    isAdd: function(value) {
      if (value) {
        this.dialogTitle = '新增客户';
      } else {
        this.dialogTitle = '编辑客户';
      }
    }
  },
  computed: mapState({
    bodyHeight: state => state.global.bodyHeight,
    cityArr: state => state.customer.provinceAndCity,
    siteArr: state => {
      let arr = [];
      let data = state.site.siteTree;
      if(data.children){
        for(var i=0;i<data.children.length;i++) {
          let item = data.children[i];
          if(item.children && item.children.length>0) {
            arr.push(item);
          }
        }
      }
      return arr;
    }
  }),
  mounted: function() {
  },

  methods: {
    openDialog() {
      this.isSubmitLoading = false;
      if (!this.isAdd) {
        this.$nextTick(() => {
          for (let item in this.sellerDetail.adminInfo) {
            this.customerInfo[item] = this.sellerDetail.adminInfo[item];
          }
          for (let item in this.sellerDetail.bankInfo) {
            this.customerInfo[item] = this.sellerDetail.bankInfo[item];
          }
          for (let item in this.sellerDetail.essentialInfo) {
            if (item !== 'cityName' && item !== 'sellerId' && item !== 'siteInfo' && item!='cityId') {
              this.customerInfo[item] = this.sellerDetail.essentialInfo[item];
            }
            if (item === 'siteInfo') {
              let site = this.sellerDetail.essentialInfo[item];
              for (let siteItem in site) {
                this.customerInfo.siteSelectArr.push(site[siteItem].id);
              }
            }
          }
          this.customerInfo.id = this.sellerDetail.essentialInfo.sellerId;
          this.customerInfo.citySelectArr = [this.sellerDetail.essentialInfo.provinceId,this.sellerDetail.essentialInfo.cityId]
        });

      }
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields();
      this.customerInfo.id = '';
      this.$emit('closeDialog');
    },
    submitCustomerForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let submitData = this.customerInfo;
          this.isSubmitLoading = true;

          submitData.siteIds = submitData.siteSelectArr.join(',');
          submitData.cityId = submitData.citySelectArr[1];
//          console.log(JSON.stringify(submitData))
          if (this.isAdd) {
            // 新增商城客户
            customerService.addSellerServer(submitData, () => {
              this.isSubmitLoading = false;
              this.$message.success('提交成功');
              this.$emit('submitSuccess');
              this.$emit('closeDialog');
            }, () => {
              this.isSubmitLoading = false;
            });
          } else {
            // 编辑商城客户
            customerService.modifySellerServer(submitData, () => {
              this.isSubmitLoading = false;
              this.$message.success('提交成功');
              this.$emit('submitSuccess');
              this.$emit('closeDialog');
            }, () => {
              this.isSubmitLoading = false;
            });
          }
        }
      });
    },
  },

  data() {
    let checkName = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的客户名称'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的客户名称'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入客户名称'));
      }
    };
    let checkCompany = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的公司名称'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的公司名称'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入公司名称'));
      }
    };
    let checkBillHeader = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的发票抬头'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的发票抬头'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入发票抬头'));
      }
    };
    let checkCreditCode = (rule, value, callback) => {
      if (value) {
        if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的社会信用代码'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入社会信用代码'));
      }
    };
    let checkContact = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的联系人'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的联系人'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入联系人'));
      }
    };
    let checkAdminName = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的超级管理员'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的超级管理员'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入超级管理员'));
      }
    };
    let checkAdminIdCard = (rule, value, callback) => {
      if (value) {
        value = value.replace(/(^\s+)|(\s+$)/g, "");
        if (value.length != 18 && value.length != 15) {
          callback(new Error('请输入正确长度的身份证号'));
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入身份证号'));
      }
    };
    let checkAdminPhone = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("^1(3|4|7|5|8)([0-9]{9}$)");
        if (!reg.test(value)) {
          callback(new Error('请输入正确格式的手机号'));
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入联系电话'));
      }
    };
    let checkBankAddress = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的所在地'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的所在地'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入所在地'));
      }
    };
    let checkBankCardNumber = (rule, value, callback) => {
      if (value) {
        var reg = /(^[0-9]{1,30}$)/;
        if (!reg.test(value)) {
          callback(new Error('请输入正确的银行卡号'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入银行卡号'));
      }
    };
    let checkContactPhone = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("(^400[0-9]{7})$|(^1(3|4|7|5|8)([0-9]{9})$)|(^0[0-9]{2,3}-[0-9]{7,8}$)");
        if (!reg.test(value)) {
          callback(new Error('请输入正确格式的联系人电话'));
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入联系人电话'));
      }
    };
    let checkOpenBankBranch = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的开户支行'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的开户支行'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入开户支行'));
      }
    };
    let checkPassword = (rule, value, callback) => {
      if (value) {
        if (value.length > 18 || value.length < 6) {
          callback(new Error('请输入6-18个字符的登录密码'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入登录密码'));
      }
    };
    let checkShopName = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的店铺名称'));
        } else if (value.length > 10) {
          callback(new Error('请输入不超过10个字符的店铺名称'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入店铺名称'));
      }
    };
    let checkTradingBank = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的交易银行'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的交易银行'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入交易银行'));
      }
    };
    return {
      options: {
        children: 'city',
        value: 'id',
        label:'name'
      },
      dialogTitle: '新增客户',
      isSubmitLoading: false,
      formDialogVisible: false,
      customerInfo: {
        sellerType:'',
        adminIdCard: '',
        adminName: '',
        adminPhone: '',
        payKey: '',
        paySecret: '',
        bankAddress: '',
        bankCardNumber: '',
        billHeader: '',
        siteIds: '',
        company: '',
        contact: '',
        contactPhone: '',
        creditCode: '',
        cityId: '',
        name: '',
        openBankBranch: '',
        password: '',
        shopName: '',
        tradingBank: '',

        siteSelectArr: [],
        citySelectArr:[]
      },
      customerInfoRules: {
        siteSelectArr: {required: true,message:'请选择服务站点',type:'array',trigger:'change'},
        citySelectArr:{ required: true,type:'array', message: '请选择所在城市',trigger:'change'},
        adminIdCard: { validator: checkAdminIdCard, trigger: 'change' },
        adminName: { validator: checkAdminName },
        adminPhone:{ validator: checkAdminPhone, trigger: 'change' },
        payKey: [
            {required:true,message:'支付Key不能为空', trigger: 'change,blur'},
            {max: 50, message: '最大长度为50', trigger: 'change,blur' }
        ],
        paySecret:  [
            {required:true,message:'支付密钥不能为空', trigger: 'change,blur'},
            {max: 50, message: '最大长度为50', trigger: 'change,blur' }
        ],
        bankAddress: { validator: checkBankAddress,trigger: 'change' },
        bankCardNumber: { validator: checkBankCardNumber,trigger: 'change'  },
        billHeader: { validator: checkBillHeader,trigger: 'change'  },
        company: { validator: checkCompany ,trigger: 'change' },
        contact: { validator: checkContact ,trigger: 'change' },
        contactPhone: { validator: checkContactPhone, trigger: 'change' },
        creditCode: [
          { validator: checkCreditCode ,trigger: 'change' }
        ],
        name: [
          { validator: checkName,trigger: 'change'  }
        ],
        openBankBranch: [
          { validator: checkOpenBankBranch,trigger: 'change'  }
        ],
        password: [
          { validator: checkPassword ,trigger: 'change' }
        ],
        shopName: [
          { validator: checkShopName,trigger: 'change'  }
        ],
        tradingBank: [
          { validator: checkTradingBank ,trigger: 'change' }
        ],
      }
    }
  }
}

</script>

<style lang="less">
@import '../../../assets/style/main.less';
.MkStoreCustomerMgt {
  h5 {
    font-size: 18px;
    font-weight: normal;
    color: @fontColorOne;
    padding: 20px 0;
  }
  h5:first-child {
    padding-top: 0;
  }
}
</style>
